<script setup lang="ts">
import type { ImageProps } from 'element-plus'
import { ElMessage } from 'element-plus'
import {
  getcommentservice,
  getdowncommentservice,
  getmenuitemListBypackIdservice,
  getuserdetailservice,
  insertcommentservice
} from "../api/food.js"
import { ref, onMounted, computed, reactive } from "vue";
import { useRoute } from "vue-router";
import {i} from "vite/dist/node/types.d-aGj9QkWt";

const routes = useRoute();
const pageSize = 4;
const currentPage = ref(1); // 当前页数
const activeNames = ref(['1'])
const comments = reactive([]);
const commenttext=ref('');
const quantity=ref(1)
const rating=ref(0);
const tableDatas=reactive([])
const fits = [
  'fill',
  'contain',
  'cover',
  'none',
  'scale-down',
] as ImageProps['fit'][];
const item = ref({
  itemid: 0,
  itemname: '',
  imageUrl: '',
  price: '',
  description: '',
});

const currentPageItems = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize;
  const endIndex = startIndex + pageSize;
  return comments.slice(startIndex, endIndex);
});

const totalItems = computed(() => comments.length);

const cardRows = computed(() => {
  const rows = [];
  for (let i = 0; i < currentPageItems.value.length; i += 4) {
    rows.push(currentPageItems.value.slice(i, i + 4));
  }
  return rows;
});

const getitem = () => {
  item.value.imageUrl = routes.query.imageUrl as string;
  item.value.itemname = routes.query.itemname as string;
  item.value.price = routes.query.price as string;
  item.value.description = routes.query.description as string;
  item.value.itemid = Number(routes.query.id);
};

onMounted(() => {
  getitem();
  getmenuListBypackId(item);
  getcomment(item).then(() => {
    getuserdetail(comments);
  });
});
const getmenuListBypackId = async (item) => {
const response = await getmenuitemListBypackIdservice(item.value.itemid);
 if (response.code === 200) {
    tableDatas.splice(0, tableDatas.length);
    response.date.forEach(item => {
      tableDatas.push(item);
    });
  }

}
const getcomment = async (item) => {
  if (item.id !== null) {
    const response = await getcommentservice(item.value.itemid);
    if (response.code === 200) {
      comments.splice(0, comments.length);
      response.date.forEach(comment => {
        // 添加一个属性来存储该一级评论关联的二级评论
        comment.commentTime=formatDateTime(comment.commentTime)
        comments.push({ ...comment, downcomments: [], showDownComments: false ,user: {},showinsertcomment: false});
      });
      return Promise.resolve(); // 确保在评论数据填充完成后返回 Promise
    }
  }
};


const getdowncomment = async (comment, item) => {
  comment.downcomments.splice(0, comment.downcomments.length);
  const response = await getdowncommentservice(comment.id, item.itemid);
  if (response.code === 200) {
    response.date.forEach(downcomment => {
      comment.downcomments.push(downcomment);
    });
    // 更新此一级评论的二级评论的可见性状态
    comment.showDownComments = true;
  }
};

const hideDownComments =(comment) => {
  console.log(comment);
  console.log(comment.showDownComments)
  comment.showDownComments = false;
}
const formatDateTime = (dateTimeStr) => {
  const date = new Date(dateTimeStr);
  return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}`;
};
const getuserdetail = async (comments) => {
  for (const comment of comments) {
    const response= await getuserdetailservice(comment.userId)
    if(response.code === 200){
      comment.user = response.date;
    }
    else {
      console.log("添加用户信息执行失败")
    }
  }

}

const showcomment = (comment) => {
  comment.showinsertcomment=!comment.showinsertcomment
}

const insercomment = async (commenttext,rating,comment)=>{
  const response = await insertcommentservice(commenttext,rating,comment.id,comment.itemId)
  if(response.code === 200){
    ElMessage({
      message: '评论成功',
      type: 'success',
    })
    comment.showinsertcomment=false;
    console.log("评论执行成功")


  }else {
    ElMessage({
      message: '评论失败请重试',
      type: 'warning',
    })
    console.log("评论执行失败")
  }

}

</script>

<template>
  <div class="common-layout">
    <el-container class="containner">
      <el-header class="containner-header">
        <el-card style="max-width: 600px">
          <template #header>
            <div class="card-itename">{{ item.itemname }}</div>
          </template>
          <img :src="item.imageUrl" style="width: 100%" />
          <p class="card-price">¥: {{ item.price }}</p>
          <div class="demo-collapse">
            <el-collapse v-model="activeNames">
              <el-collapse-item title="详情" name="1">
                <p class="collapse-p">菜品详情：   </p>

                  <el-table
                      :data="tableDatas"
                      style="width: 100%"

                  >
                    <el-table-column
                        prop="imageUrl"
                        label="图片"
                        width="180">
                      <template #default="{ row }">
                        <el-image
                            v-if="row.imageUrl"
                            :src="row.imageUrl"
                            fit="cover"
                            style="width: 50%; height: 50%;">
                <div slot="error" class="image-slot">
                  图片加载失败
                </div>
                </el-image>
</template>
</el-table-column>
<el-table-column
    prop="itemname"
    label="菜品名称"
    width="180"
>
</el-table-column>
<el-table-column

    label="数量">
  1
</el-table-column>
<el-table-column
    prop="price"
    label="价格">
</el-table-column>


</el-table>





              </el-collapse-item>
              <el-collapse-item title="评论" name="2">
                <div v-for="(row, index) in cardRows" :key="index" class="card-row">
                  <div v-for="comment in row" :key="comment.id" class="comment">
                    <p><strong>评论者：</strong>{{ comment.user.username }}</p>
                    <p><strong>评论时间：</strong>{{ comment.commentTime }}</p>
                    <p><strong>评论内容：</strong>{{ comment.comment }}</p>
                    <p><strong>评分：</strong>
                      <el-rate
                          v-model="comment.rating"
                          disabled
                          show-score
                          text-color="#ff9900"
                          score-template="{value} points"
                      /></p>

                    <div v-if="comment.showDownComments">
                      ---------------------------------------------------------------------
                      <div v-for="secondComment in  comment.downcomments" :key="secondComment.id" class="comment">
                        <p><strong>回复者：</strong>匿名会员{{secondComment.id}}</p>
                        <p><strong>评论时间：</strong>{{ secondComment.commentTime }}</p>
                        <p><strong>评论内容：</strong>{{ secondComment.comment }}</p>
                        <p><strong>评分：</strong>
                          <el-rate
                              v-model="secondComment.rating"
                              disabled
                              show-score
                              text-color="#ff9900"
                              score-template="{value} points"
                          /></p>
                        <el-button type="info" @click="hideDownComments(comment)">收起</el-button>
                        <el-divider border-style="dashed" />
                      </div>
                    </div>
                    <div>
                      <el-button type="info" class="button_comment" @click="getdowncomment(comment, item)">查看更多</el-button>
                      <el-button type="success"  @click="showcomment(comment)">回复</el-button>
                    </div>
                    <div v-show="comment.showinsertcomment">
                      <p><strong>回复内容：</strong>
                        <el-input
                            v-model="commenttext"
                            maxlength="30"
                            style="width: 240px"
                            placeholder="Please input"
                            show-word-limit
                            type="textarea"
                        /></p>
                      <p><strong>评分：</strong>
                        <el-rate v-model="rating" allow-half /></p>
                      <el-button type="success"  @click="insercomment(commenttext,rating,comment)">确认回复</el-button>
                    </div>

                    <el-divider border-style="dashed" />
                  </div>
                </div>
                <el-pagination
                    small
                    background
                    layout="prev, pager, next"
                    :total="totalItems"
                    :page-size="pageSize"
                    v-model:currentPage="currentPage"
                    class="mt-4"
                />
              </el-collapse-item>

            </el-collapse>

          </div>
        </el-card>
      </el-header>
      <el-main></el-main>
      <el-footer></el-footer>
    </el-container>

  </div>
</template>

<style scoped>
.containner { }
.containner-header {
  height: 400px;
  margin-top: 50px;
}
.card-price { color: red; }
.card-itename {
  font-family: 隶书;
  color: red;
  font-size: 100px;
}
.collapse-p {
  font-family: 隶书;
  color: darkgoldenrod;
  font-size: 20px;
}
.button_comment { margin-right: 20px; }
</style>
